import Vue from 'vue'
import {Notify} from 'vant'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/login/index.vue'
import AppSystemIndex from '@/views/system/index.vue'
import Dashboard from '@/views/dashboard/index.vue'
import strings from '@/util/strings.js'
import store from '@/vuex'
// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// eslint-disable-next-line import/no-dynamic-require
// const _import = require('./import-' + process.env.NODE_ENV)
// const _import = require.context('.', false, 'import-' + process.env.NODE_ENV)


Vue.use(VueRouter)
// const UserIndex = require('@/views/sys/user/index')
// console.log('UserIndex', UserIndex)

// 全局路由
const constantRoutes = [
  { path: '/login', component: Login, name: 'login', meta: { title: '登录' } },
]

const mainRoute = {
  path: '/',
  component: Home,
  name: 'home',
  meta: { title: '首页' },
  children: [
    {
    path: '/dashboard',
    name: 'dashboard',
    component: Dashboard,
    meta: {
      requireAuth: true,
      title: '首页'
    }
  },
  {
    path: '/app_system_index',
    name: 'app_system_index',
    component: AppSystemIndex,
    meta: {
      requireAuth: true,
      title: '个人中心'
    }
  }
  ]
}

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    component: Home,
  }
]

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: constantRoutes.concat(mainRoute)
})

let generateRouter = (menus)  => {
  let routes = []
  menus.forEach(item => {
    let route = null
    if (item.route && item.route.length > 0) {
      route = {
        name: item.route,
        path: item.route,
        // eslint-disable-next-line global-require,import/no-dynamic-require
        component: (resolve) => require([`@/views/${item.url}`], resolve),
        props: { propFlowKey: item.flowKey, propParameter: item.parameter },
        meta: {
          title: item.title,
          flowKey: item.flowKey
        }
      }
      routes.push(route)
    }
  })
  //额外添加其他路由信息
  routes.push({
    path: '/dpItem',
    name: 'dpItem',
    component: () => import('@/views/dist-pick/item.vue')
  }, {
    path: '/dPick',
    name: 'dPick',
    component: () => import('@/views/dist-pick/pick.vue')
  }, {
    path: '/transfer-pick/detail',
    name: 'editTransferPick',
    component: () => import('@/views/transfer-pick/detail.vue')
  }, {
    path: '/tpItem',
    name: 'tpItem',
    component: () => import('@/views/transfer-pick/item.vue')
  }, {
    path: '/batchAdjust',
    name: 'batchAdjust',
    component: () => import('@/views/base/batchAdjustLocation.vue')
  }, {
    path: '/fortenDataviewModel',
    name: 'fortenDataviewModel',
    component: () => import('@/components/FortenDataviewModel.vue')
  })
  return routes
}

/**
 * 仅考虑二级菜单，将二级菜单加入到路由中
 * @param {Array} menus
 */
function addDynamicRoutes(menus = []) {
  let routes = generateRouter(menus)

  mainRoute.name = 'main-dynamic'
  mainRoute.children = mainRoute.children.concat(routes)
  router.addRoutes([
    mainRoute,
    { path: '*', redirect: { name: 'PageNotFound' } }
  ])
}


router.beforeEach((to, from, next) => {
  // 如果是登录或登出，放行
  if (to.path == '/login' || to.path == '/logout') {
    next()
    return
  }

  let token = localStorage.getItem('appAuthorization')
  if (strings.isBlank(token)) {
    next({ path: '/login' })
    return
  }
  // 如果已经加载菜单列表
  if (router.options.isAddDynamicMenuRoutes) {
    store.commit('SET_WORKBENCH_ACTIVE',  to.name == 'dashboard')
    next()
    return
  }

  global.$ajax.get('/menu/getAppMenu', { params: { } }).then((response) => {
    if (response.code == 0) {
      const menus = response.data
      store.commit('SET_MENUS', menus)
      if (menus.length == 0) {
        // 没有权限，禁止登录
        next('/login')
        Notify({
          type: 'warning',
          message: '您没有可用的APP权限，请联系运营人员进行设置',
          duration: 3 * 1000
        })
        return
      }
      /*this.$router.options.routes[1].children = []
      this.generateRouter(this.menus)
      this.$router.addRoutes(this.$router.options.routes)*/

      addDynamicRoutes(menus)

      router.options.isAddDynamicMenuRoutes = true
      next({...to, replace: true })
    }
  })
})

/*const router = new VueRouter({
  routes
})*/
// router.beforeEach((to, from, next) => {
//   if (to.path === '/login' || to.path === '/logout') {
//     next()
//     return
//   }
//   // if (store.state.user.token === '') {7777777
//   //   next('/login')
//   //   // 暂时关闭登录
//   // }
//   const token = localStorage.getItem('Authorization')
//   if (token === null || token === '') {
//     next('/login')
//     return
//     // 暂时关闭登录
//   }
//   next()
// })
export default router
